#include "udpserve.hpp"
#include <map>
#include <fstream>
#include <vector>
std::map<std::string, std::string> dirction;
void init_dirctional(std::map<std::string, std::string> &dirction)
{
    std::ifstream ifdir("dirctional.txt", std::ios::in);
    std::vector<std::string> words;
    std::string buffer;
    while (getline(ifdir, buffer))
    {
        words.push_back(buffer);
    }
    for (const auto& word: words)
    {
        int pos = word.find(":");
        dirction.insert(std::make_pair(word.substr(0, pos), word.substr(pos + 1, buffer.npos)));
    }
}

void translation(std::string word, int& sockfd, sockaddr_in& client)
{    
    decltype(dirction.begin()) it = dirction.find(word);
    if(it != dirction.end())
    {
        sendto(sockfd, it->second.c_str(), it->second.size(), 0, (sockaddr*)&client, sizeof(client));
        std::cout << "翻译成功" << std::endl;
    }
    else
    {
        char buffer[255];
        sprintf(buffer, "找不到");
        sendto(sockfd, buffer, sizeof(buffer), 0, (sockaddr*)&client, sizeof(client));
    }
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        std::cout << "Usage:\n\t" << argv[0] << " local_port" << std::endl;
        exit(-1);
    }
    init_dirctional(dirction);
    // for(auto& word : dirction)
    // {
    //     std::cout << word.first << ":" << word.second << std::endl;
    // }


    uint16_t port = atoi(argv[1]);
    std::unique_ptr<udp_serve> serve(new udp_serve(translation, port));
    serve->init();
    serve->start();
    return 0;
}